package com.ruoyi.system.service;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.VideoParseResponse;
import com.ruoyi.common.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 抖音视频解析服务
 * @Author: JH-Ahua
 * @CreateTime: 2025/1/15
 */
@Service
public class DouyinService {
    
    private static final Logger logger = LoggerFactory.getLogger(DouyinService.class);
    
    /**
     * 解析抖音视频
     * @param url 抖音分享链接
     * @return 解析结果
     */

//    https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200fg10000d373euvog65mksupfiug&ratio=720p&line=0
//    https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200fg10000d373euvog65mksupfiug&ratio=720p&line=0
    public VideoParseResponse parseDouyinVideo(String url) {
        try {
            // 验证URL
            if (url == null || url.trim().isEmpty()) {
                return new VideoParseResponse(201, "URL为空", null);
            }
            
            // 提取视频ID
            String videoId = extractVideoId(url);
            if (videoId == null || videoId.isEmpty()) {
                return new VideoParseResponse(400, "无法解析视频ID", null);
            }
            
            // 构造请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0");
            
            // 请求视频信息
            String apiUrl = "https://www.iesdouyin.com/share/video/" + videoId;
            String response = HttpUtils.get(apiUrl, headers);
            
            if (response == null || response.isEmpty()) {
                return new VideoParseResponse(201, "解析数据失败", null);
            }
            
            // 解析响应数据
            JSONObject videoInfo = parseVideoInfo(response);
            if (videoInfo == null) {
                return new VideoParseResponse(201, "数据查找失败", null);
            }
            
            // 构造返回数据
            VideoParseResponse.VideoData data = buildResponseData(videoInfo);
            if (data == null) {
                return new VideoParseResponse(404, "当前分享链接已失效！", null);
            }
            
            return new VideoParseResponse(200, "解析成功", data);
            
        } catch (Exception e) {
            logger.error("解析抖音视频失败", e);
            return new VideoParseResponse(500, "解析失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 从URL中提取视频ID
     * @param url 抖音分享链接
     * @return 视频ID
     */
    private String extractVideoId(String url) {
        try {
            // 获取重定向后的最终URL
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0");
            
            String finalUrl = HttpUtils.getFinalUrl(url, headers);
            
            // 使用正则表达式提取视频ID
            Pattern pattern = Pattern.compile("[0-9]+|(?<=video/)[0-9]+");
            Matcher matcher = pattern.matcher(finalUrl);
            
            if (matcher.find()) {
                return matcher.group();
            }
            
            return null;
        } catch (Exception e) {
            logger.error("提取视频ID失败", e);
            return null;
        }
    }
    
    /**
     * 解析视频信息
     * @param response HTML响应内容
     * @return 视频信息JSON对象
     */
    private JSONObject parseVideoInfo(String response) {
        try {
            // 使用正则表达式提取window._ROUTER_DATA
            Pattern pattern = Pattern.compile("window\\._ROUTER_DATA\\s*=\\s*(.*?)</script>", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(response);
            
            if (matcher.find()) {
                String jsonStr = matcher.group(1).trim();
                JSONObject routerData = JSONObject.parseObject(jsonStr);
                
                if (routerData != null && routerData.containsKey("loaderData")) {
                    return routerData.getJSONObject("loaderData");
                }
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析视频信息失败", e);
            return null;
        }
    }
    
    /**
     * 构造响应数据
     * @param videoInfo 视频信息
     * @return 响应数据
     */
    private VideoParseResponse.VideoData buildResponseData(JSONObject videoInfo) {
        try {
            JSONObject pageData = videoInfo.getJSONObject("video_(id)/page");
            if (pageData == null || !pageData.containsKey("videoInfoRes")) {
                return null;
            }
            
            JSONObject videoInfoRes = pageData.getJSONObject("videoInfoRes");
            if (videoInfoRes == null || !videoInfoRes.containsKey("item_list")) {
                return null;
            }
            
            JSONArray itemList = videoInfoRes.getJSONArray("item_list");
            if (itemList == null || itemList.isEmpty()) {
                return null;
            }
            
            JSONObject item = itemList.getJSONObject(0);
            if (item == null) {
                return null;
            }
            
            VideoParseResponse.VideoData data = new VideoParseResponse.VideoData();
            
            // 作者信息
            JSONObject author = item.getJSONObject("author");
            if (author != null) {
                data.setAuthor(author.getString("nickname"));
                data.setUid(author.getString("unique_id"));
                JSONObject avatarMedium = author.getJSONObject("avatar_medium");
                if (avatarMedium != null && avatarMedium.containsKey("url_list")) {
                    JSONArray avatarUrls = avatarMedium.getJSONArray("url_list");
                    if (avatarUrls != null && !avatarUrls.isEmpty()) {
                        data.setAvatar(avatarUrls.getString(0));
                    }
                }
            }
            
            // 统计信息
            JSONObject statistics = item.getJSONObject("statistics");
            if (statistics != null) {
                data.setLike(statistics.getLong("digg_count"));
            }
            
            // 基本信息
            data.setTime(item.getLong("create_time"));
            data.setTitle(item.getString("desc"));
            
            // 视频信息
            JSONObject video = item.getJSONObject("video");
            if (video != null) {
                // 封面
                JSONObject cover = video.getJSONObject("cover");
                if (cover != null && cover.containsKey("url_list")) {
                    JSONArray coverUrls = cover.getJSONArray("url_list");
                    if (coverUrls != null && !coverUrls.isEmpty()) {
                        data.setCover(coverUrls.getString(0));
                    }
                }
                
                // 视频播放地址
                JSONObject playAddr = video.getJSONObject("play_addr");
                if (playAddr != null && playAddr.containsKey("url_list")) {
                    JSONArray playUrls = playAddr.getJSONArray("url_list");
                    if (playUrls != null && !playUrls.isEmpty()) {
                        String videoUrl = playUrls.getString(0);
                        // 替换 "playwm" 为 "play" 去除水印
                        videoUrl = videoUrl.replace("playwm", "play");
                        data.setUrl(videoUrl);
                    }
                }
            }
            
            // 图片信息（图集）
            JSONArray images = item.getJSONArray("images");
            if (images != null && !images.isEmpty()) {
                List<String> imageUrls = new ArrayList<>();
                for (int i = 0; i < images.size(); i++) {
                    JSONObject image = images.getJSONObject(i);
                    if (image != null && image.containsKey("url_list")) {
                        JSONArray imageUrlList = image.getJSONArray("url_list");
                        if (imageUrlList != null && !imageUrlList.isEmpty()) {
                            imageUrls.add(imageUrlList.getString(0));
                        }
                    }
                }
                if (!imageUrls.isEmpty()) {
                    data.setImages(imageUrls);
                    data.setUrl("当前为图文解析，图文数量为:" + imageUrls.size() + "张图片");
                }
            } else {
                data.setImages("当前为短视频解析模式");
            }
            
            // 音乐信息
            JSONObject music = item.getJSONObject("music");
            if (music != null) {
                VideoParseResponse.Music musicInfo = new VideoParseResponse.Music();
                musicInfo.setTitle(music.getString("title"));
                musicInfo.setAuthor(music.getString("author"));
                
                JSONObject coverLarge = music.getJSONObject("cover_large");
                if (coverLarge != null && coverLarge.containsKey("url_list")) {
                    JSONArray musicCoverUrls = coverLarge.getJSONArray("url_list");
                    if (musicCoverUrls != null && !musicCoverUrls.isEmpty()) {
                        musicInfo.setAvatar(musicCoverUrls.getString(0));
                    }
                }
                
                if (video != null) {
                    JSONObject playAddr = video.getJSONObject("play_addr");
                    if (playAddr != null) {
                        musicInfo.setUrl(playAddr.getString("uri"));
                    }
                }
                
                data.setMusic(musicInfo);
            } else {
                data.setMusic("音乐为视频原声");
            }
            
            return data;
            
        } catch (Exception e) {
            logger.error("构造响应数据失败", e);
            return null;
        }
    }
}
